import { Component } from '@angular/core';
import * as echarts from 'echarts';
import { WorkbenchService } from 'src/app/@core/mock/datasERVICE/workbench.service';

@Component({
  selector: 'app-purchase-workbench',
  templateUrl: './purchase-workbench.component.html',
  styleUrls: ['./purchase-workbench.component.scss']
})
export class PurchaseWorkbenchComponent {
  amountData: any = {
    "totalPurchaseOrderAmount": 0, // 总采购订单金额
    "totalPurchaseArrivalAmount": 0, // 总采购到货金额
    "monthPurchaseOrderAmount": 0, // 本月采购订单金额
    "monthPurchaseArrivalAmount": 0, // 本月采购到货金额
    "monthPurchaseReturnAmount": 0, // 本月采购退货金额
    "monthPurchaseDeliveryRate": 0, // 本月采购交付率
    "purchaseOrderMonthUpRate": 0, // 采购订单月环比增长率
    "purchaseArrivalMonthUpRate": 0, // 采购到货月环比增长率
    "purchaseReturnMonthUpRate": 0, // 采购退货月环比增长率
    "purchaseDeliveryRateMonthUpRate": 0 // 采购交付月环比增长率
  }
  todoList: any = {
    "allPurchaseTasksCount": 72,
    "purchaseRequireTasksCount": 20,
    "purchaseOrdeTasksrCount": 18,
    "purchaseDeliveryTasksCount": 28,
    "purchaseReturnTasksCount": 6
  }
  statistics = []
  isFinished = {
    "purchaseFinishedCount": 0,
    "purchaseUnFinishedCount": 0
  }
  monthArrivalAmount: any = []
  purchaseReturn = []
  constructor(private workbenchService: WorkbenchService) { }
  ngOnInit(): void {
    this.workbenchService.getPurchaseAmountData().subscribe((res: any) => {
      this.amountData = res
    })
    this.workbenchService.getPurchaseToDoList().subscribe((res: any) => {
      this.todoList = res
    })
    this.workbenchService.getPurchaseStatistics().subscribe((res: any) => {
      this.statistics = res
      this.saleData()
    })
    // this.workbenchService.getPurchaseIsFinished().subscribe((res: any) => {
    //   this.isFinished = res
    //   this.deliveryData()
    // })
    this.workbenchService.getMonthArrival().subscribe((res: any) => {
      const currentMonth = new Date().getMonth(); // 获取当前月份（0-11，0表示1月，11表示12月）

      // 过滤数据，只保留当前月份及其前两个月的数据
      this.monthArrivalAmount = res.filter((item: any, index: number) => {
        return index >= currentMonth - 2 && index <= currentMonth;
      });
      this.renderChart(this.monthArrivalAmount)
    })
    this.workbenchService.IsReturned().subscribe((res: any) => {
      const currentMonth = new Date().getMonth(); // 获取当前月份（0-11，0表示1月，11表示12月）

      // 过滤数据，只保留当前月份及其前两个月的数据
      this.purchaseReturn = res.filter((item: any, index: number) => {
        return index >= currentMonth - 2 && index <= currentMonth;
      });

      this.renderAfterSalesChart();
    })
  }
  ngAfterViewInit(): void {
    setTimeout(() => {
      this.renderAfterSalesChart();
    }, 0);
  }
  saleData() {
    const quantities = this.statistics.map(item => item.monthPurchaseAmount);
    const growthRates = quantities.map((value, index, array) => {
      if (index === 0) return 0; // 第一个月没有增长率
      const growthRate = ((value - array[index - 1]) / array[index - 1] * 100).toFixed(2)
      return isNaN(Number(growthRate)) || !isFinite(Number(growthRate)) ? 0 : Number(growthRate); // 计算增长率并保留两位小数，如果计算不出来则为0
    })
    const maxQuantity = Math.max(...quantities)
    // 将最大值转换为万位数加1，后面补0的格式
    const formattedMaxQuantity = Math.ceil(maxQuantity / 10000) * 10000
    // 找到最大和最小增长率
    const maxGrowthRate = Math.max(...growthRates)
    const minGrowthRate = Math.min(...growthRates)
    // 将最大和最小增长率的十位取整加1
    const adjustedMaxGrowthRate = Math.ceil(maxGrowthRate / 10) * 10 + 10
    const adjustedMinGrowthRate = Math.ceil(minGrowthRate / 10) * 10 + 10
    // 取绝对值并相加
    const result = Math.abs(adjustedMaxGrowthRate) + Math.abs(adjustedMinGrowthRate)
    const option = {
      tooltip: {
        show: true,
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
        },
      },
      grid: {
        left: '5%',
        right: '5%',
        bottom: '5%',
        top: '12%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      },
      yAxis: [
        {
          type: 'value',
          name: '采购额(元)',
          axisLine: {
            show: true,
          },
          axisLabel: {
            formatter: '{value} 元'
          },
          splitNumber: 5, // 设置左侧 y 轴的刻度数量
          min: 0, // 设置最小值
          interval: formattedMaxQuantity / 5 // 设置间隔
        },
        {
          type: 'value',
          name: '增长率(%)',
          axisLine: {
            show: true,
          },
          axisLabel: {
            formatter: '{value} %'
          },
          splitNumber: 5, // 设置右侧 y 轴的刻度数量
        }
      ],
      series: [
        {
          data: quantities,
          name: "采购额(元)",
          barWidth: '50%',
          type: 'bar',
          label: {
            show: true,
            position: 'top',
            formatter: function (params: any) {
              return `${params.value} 元`;
            }
          },
        },
        {
          data: growthRates,
          name: "增长率(%)",
          type: 'line',
          smooth: true,
          yAxisIndex: 1, // 使用第二个 y 轴
        }
      ]
    }
    const myChart = echarts.init(document.getElementById('xiaoshoue') as HTMLElement)
    myChart.setOption(option)
    myChart.resize() // 初始化后立即调用 resize 方法
    window.addEventListener('resize', function () {
      myChart.resize();
    })
  }
  // deliveryData() {
  //   const categories = ['已到货', '未到货']
  //   const option = {
  //     tooltip: {
  //       trigger: 'axis',
  //       axisPointer: {
  //         type: 'shadow'
  //       }
  //     },
  //     grid: {
  //       left: '3%',
  //       right: '4%',
  //       bottom: '3%',
  //       containLabel: true
  //     },
  //     xAxis: {
  //       type: 'category',
  //       data: categories,
  //       name: "状态"
  //     },
  //     yAxis: {
  //       type: 'value',
  //       name: "数量"
  //     },
  //     series: [
  //       {
  //         name: '数量',
  //         type: 'bar',
  //         barWidth: '30%',
  //         data: [
  //           {
  //             value: this.isFinished.purchaseFinishedCount,
  //             itemStyle: { color: '#2ca02c' } // 绿色
  //           },
  //           {
  //             value: this.isFinished.purchaseUnFinishedCount,
  //             itemStyle: { color: '#bcbd22' } // 黄色
  //           }
  //         ]
  //       }
  //     ]
  //   }
  //   const myChart = echarts.init(document.getElementById('jiaofu') as HTMLElement)
  //   myChart.setOption(option)
  //   myChart.resize() // 初始化后立即调用 resize 方法
  //   window.addEventListener('resize', function () {
  //     myChart.resize()
  //   })
  // }
  renderChart(data: any) {
    const months = data.map((item: any) => item.month)
    const totalRequiredArrival = data.map((item: any) => item.totalRequiredArrival)
    const totalArrived = data.map((item: any) => item.totalArrived)
    const totalUnarrived = data.map((item: any) => item.totalUnarrived)
    const arrivedOverdue = data.map((item: any) => item.arrivedOverdue)
    const unarrivedOverdue = data.map((item: any) => item.unarrivedOverdue)
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['需到货数', '已到货数', '未到货数', '已到货(逾期)', '未到货(逾期)'],
        right: '0%'
      },
      grid: {
        left: '0%',
        right: '0%',
        top: "30%",
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: months,
        name: "月份"
      },
      yAxis: {
        type: 'value',
        name: "数量"
      },
      series: [
        {
          name: '需到货数',
          type: 'bar',
          data: totalRequiredArrival,
          itemStyle: { color: '#2ca02c' } // 绿色
        },
        {
          name: '已到货数',
          type: 'bar',
          data: totalArrived,
          itemStyle: { color: '#1f77b4' } // 蓝色
        },
        {
          name: '未到货数',
          type: 'bar',
          data: totalUnarrived,
          itemStyle: { color: '#ff7f0e' } // 橙色
        },
        {
          name: '已到货(逾期)',
          type: 'bar',
          data: arrivedOverdue,
          itemStyle: { color: '#d62728' } // 红色
        },
        {
          name: '未到货(逾期)',
          type: 'bar',
          data: unarrivedOverdue,
          itemStyle: { color: '#9467bd' } // 紫色
        }
      ]
    }
    const myChart = echarts.init(document.getElementById('jiaofu') as HTMLElement)
    myChart.setOption(option)
    myChart.resize()// 初始化后立即调用 resize 方法
    window.addEventListener('resize', function () {
      myChart.resize()
    })
  }
  renderAfterSalesChart() {
    const months = this.purchaseReturn.map((item: any) => item.month)
    const returnData = this.purchaseReturn.map((item: any) => item.purchaseReturnCount)
    const growthRateData = this.purchaseReturn.map((item: any) => item.purchaseReturnGrowthRate)
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['退货数量', '增长率']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: months
      },
      yAxis: [
        {
          type: 'value',
          name: '退货数量',
          position: 'left'
        },
        {
          type: 'value',
          name: '增长率',
          position: 'right',
          axisLabel: {
            formatter: '{value} %'
          }
        }
      ],
      series: [
        {
          name: '退货数量',
          type: 'bar',
          data: returnData
        },
        {
          name: '增长率',
          type: 'line',
          yAxisIndex: 1,
          color: "#ff4a4f",
          data: growthRateData
        }
      ]
    }
    const myChart = echarts.init(document.getElementById('afterSalesChart') as HTMLElement)
    myChart.setOption(option)
    myChart.resize() // 初始化后立即调用 resize 方法
    window.addEventListener('resize', function () {
      myChart.resize();
    })
  }
}
